package com.edais.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

/**
 * 使用FastDFS对分布式文件上传下载
 * */
public class FastDFSUtil {
	private static final Logger log = Logger.getLogger(FastDFSUtil.class);
	private File configFile;
	private String groupName;

	public byte[] getFileBuffer(InputStream is, int len) throws IOException{
		byte[] buf=new byte[len];
		is.read(buf);
		return buf;
	}

	/**
	 * 文件上传
	 * @param File:上传文件
	 * @param uploadFileName:上传文件的文件名,例"test.jpg"
	 * @return 返回文件的服务器路径(该路径直接复制,可用来下载)
	 * */
	public String upload(File file, String uploadFileName) throws IOException, MyException {
		InputStream inStream  = new FileInputStream(file);
		long fileLength = file.length();
		
		byte[] fileBuff = getFileBuffer(inStream, (int) fileLength);
		String fileId = "";
		String fileExtName = "";
		if (uploadFileName.contains(".")) {
			fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
		} else {
			log.info("Fail to upload file, because the format of filename is illegal.");
			return fileId;
		}

		// 建立连接
		//ClientGlobal.init(this.getClass().getClassLoader().getResource(configFile).getPath());
		ClientGlobal.init(configFile.getAbsolutePath());
		TrackerClient tracker = new TrackerClient();
		TrackerServer trackerServer = tracker.getConnection();
		StorageServer storageServer = null;
		StorageClient1 client = new StorageClient1(trackerServer, storageServer);

		// 设置元信息
		NameValuePair[] metaList = new NameValuePair[3];
		metaList[0] = new NameValuePair("fileName", uploadFileName);
		metaList[1] = new NameValuePair("fileExtName", fileExtName);
		metaList[2] = new NameValuePair("fileLength",String.valueOf(fileLength));

		// 上传文件
		try {
			fileId = client.upload_file1(groupName,fileBuff, fileExtName, metaList);
		} catch (Exception e) {
			log.error("Upload file \"" + uploadFileName + "\"fails");
		}
		inStream.close();
		trackerServer.close();
		return fileId;
	}
	
	/**
	 * 文件上传
	 * @param fullPathfileName:上传文件的全路径,例"d:\\test.jpg"
	 * @param uploadFileName:上传文件的文件名,例"test.jpg"
	 * @return 返回文件的服务器路径(该路径直接复制,可用来下载)
	 * */
	public String upload(String fullPathfileName, String uploadFileName) throws IOException, MyException {
		File file = new File(fullPathfileName);
		InputStream inStream  = new FileInputStream(file);
		long fileLength = file.length();

		byte[] fileBuff = getFileBuffer(inStream, (int) fileLength);
		String fileId = "";
		String fileExtName = "";
		if (uploadFileName.contains(".")) {
			fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
		} else {
			log.info("Fail to upload file, because the format of filename is illegal.");
			return fileId;
		}

		// 建立连接
		ClientGlobal.init(this.getClass().getClassLoader().getResource("fastdfs.conf").getPath());
//		ClientGlobal.init(configFile.getAbsolutePath());
		TrackerClient tracker = new TrackerClient();
		TrackerServer trackerServer = tracker.getConnection();
		StorageServer storageServer = null;
		StorageClient1 client = new StorageClient1(trackerServer, storageServer);

		// 设置元信息
		NameValuePair[] metaList = new NameValuePair[3];
		metaList[0] = new NameValuePair("fileName", uploadFileName);
		metaList[1] = new NameValuePair("fileExtName", fileExtName);
		metaList[2] = new NameValuePair("fileLength",String.valueOf(fileLength));

		// 上传文件
		try {
			fileId = client.upload_file1(groupName,fileBuff, fileExtName, metaList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("Upload file \"" + uploadFileName + "\"fails");
		}
		inStream.close();
		trackerServer.close();
		return fileId;
	}

	public  String uploadPic(byte[] pic, String uploadFileName, long size) throws IOException, MyException {
		   		String fileId = "";
				String fileExtName = "";
				if (uploadFileName.contains(".")) {
					fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
				} else {
					log.info("Fail to upload file, because the format of filename is illegal.");
					return fileId;
				}

				// 建立连接
//				ClientGlobal.init(this.getClass().getClassLoader().getResource("fastdfs.conf").getPath());
				ClientGlobal.init(configFile.getAbsolutePath());
				TrackerClient tracker = new TrackerClient();
				TrackerServer trackerServer = tracker.getConnection();
				StorageServer storageServer = null;
				StorageClient1 client = new StorageClient1(trackerServer, storageServer);

				// 设置元信息
				NameValuePair[] metaList = new NameValuePair[3];
				metaList[0] = new NameValuePair("fileName", uploadFileName);
				metaList[1] = new NameValuePair("fileExtName", fileExtName);
				metaList[2] = new NameValuePair("fileLength",String.valueOf(size));

				// 上传文件
				try {
					fileId = client.upload_file1(groupName,pic, fileExtName, metaList);
					log.debug("fileId:"+fileId);
				} catch (Exception e) {
					e.printStackTrace();
					log.error("Upload file \"" + uploadFileName + "\"fails");
				}
				trackerServer.close();
				return fileId;
		    }
	/**
	 * 文件下载
	 * @param fileName:文件在服务器的位置:例"M00/00/00/rBEiZlNcwJ6x0hyuAABTb_F6UwE363.jpg"
	 * @return 返回用于流输出的byte数组;该byte数组可以直接放到流中输出
	 * 
	 * TODO:
	 * fileName:该字段需要后期优化,主要原因如下:
	 * 上传时,返回路径为:group1/M00/00/00/rBEiZlNcwJ6x0hyuAABTb_F6UwE363.jpg
	 * 下载时,正确路径为:M00/00/00/rBEiZlNcwJ6x0hyuAABTb_F6UwE363.jpg(前面的group1/是多余的,需要去掉)
	 * */
	public byte[] download(String fileName) throws Exception{
		if(fileName!= null && fileName.length() > 7) {
			fileName = fileName.substring(7);//TODO 此处需要后期优化
		}else {
			log.debug("error message >>>>>>>>>>fileName is null or fileName <= 7");
			return null;
		}
		try {
            ClientGlobal.init(configFile.getAbsolutePath());
            TrackerClient tracker = new TrackerClient(); 
            TrackerServer trackerServer = tracker.getConnection(); 
            StorageServer storageServer = null;

            StorageClient storageClient = new StorageClient(trackerServer, storageServer); 
            byte[] b = storageClient.download_file(groupName, fileName);
            return b;
        } catch (Exception e) { 
            log.error("下载文件异常",e);
            throw e;
        }
	}
	
	public static void main(String[] args)throws Exception{
		 FastDFSUtil fastDFSUtil=new FastDFSUtil();
		 String filepath="d:\\test2.jpg";
		 String fileName="2017216test.jpg";
		 try {
			 fastDFSUtil.upload(filepath,fileName);
		 }catch (Exception e){
		 	e.printStackTrace();;
		 }

	}
	
	public File getConfigFile() {
		return configFile;
	}

	public void setConfigFile(File configFile) {
		this.configFile = configFile;
	}

	public String getGroupName() {
		return groupName;
	}

	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}


}
